#ifndef NETWORKMANAGER_H
#define NETWORKMANAGER_H


#include <Arduino.h>
#include <SPIFFS.h>
#include <WiFi.h>
#include "../shared_values.h"
// 读取WiFi名称和密码并尝试连接WiFi
bool wifi_initalize_from_file(){
     
  static String ssid;
  static String password;
  if (SPIFFS.exists("/wifi.txt")) {
    Serial.println("[XTouch][FS] wifi.txt文件存在");
    fs::File wifiFile = SPIFFS.open("/wifi.txt", "r");
    ssid = wifiFile.readStringUntil('\n');
    password = wifiFile.readStringUntil('\n');
    ssid.trim();
    password.trim();
    wifiFile.close();
    WiFi.begin(ssid.c_str(), password.c_str());    // 连接WiFi网络
    Serial.printf("[XTouch][NETWORK] 正在连接WiFi %s", ssid.c_str());
    unsigned long startAttemptTime = millis(); // 记录开始尝试连接的时间
    while (millis() - startAttemptTime < 5000) { // 等待WiFi连接成功或超时
      if (WiFi.status() != WL_CONNECTED){
        Serial.println("[XTouch][NETWORK] 正在连接WiFi...");
        delay(100);
      } else {
        Serial.println("WiFi连接成功");
        global_ssid = ssid.c_str();
        global_password = password.c_str();
        return true;
      }
    }
    Serial.println("WiFi连接超时");
    return false;
  } else {
    Serial.println("[XTouch][FS] wifi.txt文件不存在");
    return false;
  }
}

void wifi_save_to_file(const char* newSSID, const char* newPassword){
    fs::File wifiFile = SPIFFS.open("/wifi.txt", "w");
    wifiFile.println(newSSID);
    wifiFile.println(newPassword);
    wifiFile.close();
}


#endif // NETWORKMANAGER_H